/** 倒计时 */
export const countDown = (
  time: number,
  handler: (t: number) => void,
  endHandler: () => void,
) => {
  let timer: number;
  // 初始时间戳
  const initTimeStamp = Date.now();
  // 终点时间戳
  const targetTimeStamp = initTimeStamp + time * 1000;
  // 定时器间隔
  const timeStep = 1000;
  function main() {
    timer = setTimeout(() => {
      const nowTimeStamp = Date.now();
      if (targetTimeStamp - nowTimeStamp > 0) {
        const newTime = Math.round((targetTimeStamp - nowTimeStamp) / 1000);
        handler(Math.max(newTime, 0));
        main();
      } else {
        handler(0);
        endHandler();
      }
    }, timeStep) as unknown as number;
  }
  // 修复倒计时误差
  main();
  return () => clearTimeout(timer);
};
